package com.small.admin.service.impl;

import com.small.admin.dto.RoleStore;
import com.small.admin.entity.RoleAdmin;
import com.small.admin.entity.RoleMenu;
import com.small.admin.mapper.RoleAdminMapper;
import com.small.admin.mapper.RoleMenuMapper;
import org.springframework.stereotype.Service;
import com.small.common.base.service.impl.BaseServiceImpl;
import com.small.admin.entity.Role;
import com.small.admin.mapper.RoleMapper;
import com.small.admin.service.RoleService;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

/**
 * 作者: fenny
 * 邮箱: 893146555@qq.com
 * 时间: 2017-10-17 15:28:29
 * 描述: 角色
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private RoleAdminMapper roleAdminMapper;

    @Override
    public void add(RoleStore roleStore) {
        insert(roleStore);
        addRoleMenu(roleStore);
    }

    @Override
    public void update(RoleStore roleStore) {
        updateSelectiveById(roleStore);
        //删除关系
        Example example = new Example(RoleMenu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleId", roleStore.getId());
        roleMenuMapper.deleteByExample(example);
        //添加关系
        addRoleMenu(roleStore);
    }

    @Override
    public int deleteById(Object id) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        //不能删除系统角色
        criteria.andNotEqualTo("isSystem", 1);
        mapper.deleteByExample(example);
        int result = super.deleteById(id);
        if (result > 0) {
            //删除角色与用户的关联
            Example roleAdminEx = new Example(RoleAdmin.class);
            Example.Criteria roleAdminCr = roleAdminEx.createCriteria();
            roleAdminCr.andEqualTo("roleId", id);
            roleAdminMapper.deleteByExample(roleAdminEx);
            //删除角色与菜单的关联
            Example roleMenuEx = new Example(RoleMenu.class);
            Example.Criteria roleMenuCr = roleAdminEx.createCriteria();
            roleMenuCr.andEqualTo("roleId", id);
            roleMenuMapper.deleteByExample(roleMenuEx);

        }
        return result;
    }

    private void addRoleMenu(RoleStore roleStore) {
        if (roleStore.getMenuIds() != null) {
            RoleMenu roleMenu = new RoleMenu();
            for (Long menuId : roleStore.getMenuIds()) {
                roleMenu.setRoleId(roleStore.getId());
                roleMenu.setMenuId(menuId);
                roleMenuMapper.insert(roleMenu);
            }
        }
    }
}